package ws

import (
	"bytes"
	"dgo/MyProj/PrjRPC"
	"dgo/goutils/utils"
	"fmt"
	"strings"
)

type RPCWsCltEngine struct {
	id         string
	rpc        *PrjRPC.RPC
	rpcwsclt   *WsClient
	rpcclt_cmd *PrjRPC.RPCCmdRec
}

func NewRPCWscltEngine(id string, ws_req_uri, origin string) *RPCWsCltEngine {
	rval := &RPCWsCltEngine{
		id:       id,
		rpcwsclt: NewWsClient(ws_req_uri, origin),
	}
	return rval
}

func (this *RPCWsCltEngine) Start() {
	this.rpcwsclt.OnRecv = this.OnWsCltBaseCmdRecv
	this.rpcwsclt.OnConnect = func(sender *WsClient) {
		sender.SendMsg(1, []byte(fmt.Sprintf("%s:%s", this.id, utils.NowString())))
	}
	this.rpcclt_cmd = this.rpc.CheckGetCmdRec(this.id)
	this.rpcclt_cmd.SendFuncAssign(func(data []byte) error {
		return this.rpcwsclt.SendMsg(2, data)
	})

	this.rpcwsclt.Start()
}

func (this *RPCWsCltEngine) SetRPC(rpc *PrjRPC.RPC) {
	this.rpc = rpc
}

func (this *RPCWsCltEngine) OnWsCltBaseCmdRecv(sender *WsClient, msgtype byte, msg []byte) {
	if msgtype == 1 {
		str := string(msg)
		strs := strings.SplitN(str, ",", 2)
		if len(strs) == 1 {
			this.rpc.Invoke_rp_func(this.rpcclt_cmd, strs[0], "")
		} else {
			this.rpc.Invoke_rp_func(this.rpcclt_cmd, strs[0], strs[1])
		}
	} else { // BinaryMessage
		nbuf := bytes.SplitN(msg, buf_spliter, 2)
		id := string(nbuf[0])
		if len(nbuf) > 1 {
			this.rpc.Invoke_rp_func(this.rpcclt_cmd, id, nbuf[1])
		} else {
			this.rpc.Invoke_rp_func(this.rpcclt_cmd, id, "")
		}
	}
}
